package com.hongxin.nw.netty.handle;

import com.hongxin.nw.netty.utils.BinaryTools;
import com.hongxin.nw.netty.values.TypeIdentif;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 合法包长度
 */
@Slf4j
public class CustomDecoder extends LengthFieldBasedFrameDecoder {

    //头部信息的大小应该是 启动符 + 长度域 + 控制域 = 7
    private final static int HEADER_SIZE = 7;

    public CustomDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,
                         int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength,
                lengthAdjustment, initialBytesToStrip, failFast);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf)msg;
        String data = BinaryTools.subByteBuf(in.readableBytes(),0,in);
        log.info("->{}", data);
        super.channelRead(ctx, msg);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in){
        in.markReaderIndex();
        if (in.readableBytes() < HEADER_SIZE) {// in == null ||
            log.info("数据不能为空,且不能小于头部长度({})",HEADER_SIZE);
            return null;
        }
        int startByte = Integer.parseInt(BinaryTools.subByteBuf(1,0,in));
        if(startByte != TypeIdentif.IDENTIFY_START.getInt()){
            in.readByte();
            log.info("协议头错误, 处理异常数据包中...");
            return null;
        }
        int realLength = Integer.parseInt(BinaryTools.converter(BinaryTools.subByteBuf(2,1,in)),16);
        if (in.readableBytes() < realLength + 3){
            log.info("数据接收中...");
            return null;
        }
        return in.readBytes(in.readableBytes());
    }

}